import { Component, Emit, Prop, Watch } from 'vue-facing-decorator'
import Render from '@/render/Render'
import toNative from '@/utils/toNative'
import Drawer from '@/components/drawer/Index'
import FilterRender from '@/render/FilterRender'
import renderModal, {
    getModelValue,
    initModelValue,
    renderForm,
    type FormModalDto
} from '@/components/modal/Modal'
import type { PeriodUtdangerListStaffDto, UploadPeriodInsuranceDto } from '@/api/insurance/period/types'
import {
    addPeriodInsuranceCase,
    getPeriodUtdangerListStaff,
    uploadPeriodInsuranceVideo
} from '@/api/insurance/period/index'
import { wait, downloadBlobString,dateFormat } from '@/utils/util'
import { nextTick } from 'vue'
import { Button, message } from 'ant-design-vue'
import { RedoOutlined, DownloadOutlined } from '@ant-design/icons-vue'

// AddClaimsPop

@Component
export class AddClaimsPop extends FilterRender { 
    fileList = [] as UploadPeriodInsuranceDto[]
    @Prop() show!: boolean
    @Prop() type!: string
    showDrawer = false


   @Emit('update:show')
    updateShow(val: boolean) {
        return val
    }

    @Emit('change')
   handleChange() {
       return 
   }

    @Watch('show', { immediate: true })
    handleWatchShow() {
        this.showDrawer = this.show
    }

    @Watch('showDrawer', { immediate: true })
    handleWatchShowDialog() {
        this.updateShow(this.showDrawer)
    }
    
    formConfig = this.initFormConfig() as FormModalDto
    initFormConfig() {
        return {
            title: '',
            width: '400px',
            theme: 'light',
            show: true,
            labelCol: {
                style: {
                    width: '8em'
                }
            },
            items: {
                companyId: {
                    name: '报案公司',
                    element: 'select',
                    placeholder: '请输入报案公司名称',
                    optionsType: 'company',
                    required: true
                },
                fileList: {
                    name: '上传受伤者视频',
                    element: 'upload',
                    type: 'text',
                    params: {
                        autoUpload: false,
                        type: 'text',
                        accept: '.mp4',
                        limit: 5,
                        maxSize: '10000000',
                        isCurrent: true,
                        suffix:'视频时长10s-60s ，大小不超100M'
                    },
                    callback: {
                        change: this.onUploadChange
                    },
                },
                recordId:{ 
                    name: '出险人',
                    element: 'select',
                    placeholder: '请选择出险人',
                    required: true,
                    remote: true,
                    options: [],
                    params: {
                        method: async (event: string) => {
                            const { items } = this.formConfig
                            const params = getModelValue(this.formConfig)
                            if (event && params.companyId) {
                                const res = await getPeriodUtdangerListStaff({
                                    companyId: params.companyId,
                                    searchUserInfo: event,
                                    isAdmin: 1
                                })
                                items.recordId.options = res.list.map((item:PeriodUtdangerListStaffDto) => ({
                                    label: `${ item.userName }（${ item.idCardNo.slice(-4) }）投保时间：${ item.insurStartTime }`,
                                    value: item.id,
                                    name: item.userName
                                }))
                            }
                            if (!params.companyId) { 
                                message.info('请先选择报案公司')
                            }
                        }
                    },
                },
                outDangerPhone:{ 
                    name: '出险人手机号',
                    element: 'input',
                    placeholder: '请输入手机号',
                    required: true,
                    params: {
                        maxlength:11
                    }
                },
                outDangerDate:{ 
                    name: '出险时间',
                    element: 'datetime',
                    type: 'datetime',
                    value: '',
                    required: true,
                    params: {
                        valueFormat: 'YYYY-MM-DD HH:mm:ss',
                        maxDateTime: dateFormat(new Date(),'YYYY-MM-DD') 
                    }
                },
                accidentType: {
                    name: '事故类型',
                    element: 'select',
                    required: true,
                    options: [
                        {label: '工伤',value: 2, },
                        {label: '意外',value: 1, },
                    ]
                },
                hurtStatus: {
                    name: '是否有骨折或更严重伤情',
                    element: 'select',
                    required: true,
                    options: [
                        {label: '是',value: 1, },
                        {label: '不是',value: 2, },
                    ]
                },
                hospitalStatus: {
                    name: '是否住院',
                    element: 'select',
                    required: true,
                    options: [
                        {label: '是',value: 1, },
                        {label: '不是',value: 2, },
                    ]
                    
                },
                outDangerPlace:{ 
                    name: '出险地点',
                    element: 'input',
                    placeholder: '请输入出险地点，如xx公司xx车间',
                    required: true
                },
                visitHospital:{ 
                    name: '就诊医院',
                    element: 'input',
                    placeholder: '如：昆山市打第一人民医院',
                    required: true
                },
                accidentDetails:{ 
                    name: '详细事故经过',
                    element: 'input',
                    placeholder: '请输入详细事故经过',
                    required: true
                },
                reportPhone:{ 
                    name: '报案人电话',
                    element: 'input',
                    placeholder: '请输入报案人电话',
                    required: true
                },
            },
            complete: async () => {},
            cancel: () => {},
        } as FormModalDto
    } 

    // 上传方法
    async onUploadChange(event: { current: { base64:string, raw:File,operationType:string }, fileList: { url: string, base64: string, uid: number }[] }) {
        await wait(200)
        const { current, fileList } = event
        console.log(current, 'currentcurrent')
        if (current.operationType === 'add') { 
            const formData = new FormData()
            formData.append('file', current.raw)
            const result = await uploadPeriodInsuranceVideo(formData)
            result['name'] = new Date().getTime() + ''
            this.fileList.push(result)
            this.formConfig.items.fileList.value = this.fileList.map((item: UploadPeriodInsuranceDto) => {
                return {
                    id: item.name,
                    name: item.name + '.mp4',
                    url: item.fileUrl,
                    fileSize:item.fileSize
                }
            })
            console.log(this.formConfig, 'this.formConfig')
        }
    }

    // 提交
    async onSubmit() {
        await this.basicForm.validate()
        const params = getModelValue(this.formConfig)
        console.log(params, '点击了123')
        params.params = {photos: {}}
        params.outDangerUserName = this.formConfig.items.recordId.options?.filter(item => item.value === params.recordId)[0].name
        if (params.fileList.length > 0) { 
            params.params.photos = params.fileList.map((item:UploadPeriodInsuranceDto) => { 
                return {
                    fileType: 'video/mp4',
                    fileUrl: item.url,
                    name: item.name,
                    size: item.fileSize,
                    url: item.url
                }
            })
        }
        params.isAdmin = 1
        delete params.fileList
        console.log(params, '点击了456')
        await addPeriodInsuranceCase(params)
        message.success('提交成功')
        this.showDrawer = false
        this.handleChange()
        initModelValue(this.formConfig)
    }
    basicForm = {
        validate: async () => {

        },
        clear: () => {},
        element: () => <> </>
    }
    
    
    created() { 
        this.basicForm = renderForm(this.formConfig)
    }

    render() {
        return (
            <>
                {/* {this.renderFilter()} */}
                <Drawer v-model:show={this.showDrawer} title="新增长期保报案" size="700" height="100%" v-slots={{
                    footer: () => {
                        return <div>
                            <Button type="primary" onClick={this.onSubmit}>提交</Button>
                        </div>
                    }
                }}>
                    <div>
                        { this.basicForm.element() }
                    </div>
                </Drawer>
            </>
        )
    }
}

export default toNative<{}, {change: () => void}>(AddClaimsPop)